﻿import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import type { ApiResponse, ApiError } from '@/types/api'
<#if enableSecurity>
import { useAuthStore } from '@/stores/auth'
import router from '@/router'
</#if>

const TENANT_HEADER = 'X-Tenant-Id'
<#if enableSecurity>
interface RetriableRequestConfig extends InternalAxiosRequestConfig {
  _retry?: boolean
}
</#if>

const createRequest = (): AxiosInstance => {
  const instance = axios.create({
    baseURL: '/api',
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })

  instance.interceptors.request.use(
    (config) => {
<#if enableSecurity>
      const authStore = useAuthStore()
      if (authStore.isAuthenticated) {
        config.headers = config.headers || {}
        const token = authStore.getAccessToken()
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        const tenantId = authStore.getTenantId()
        if (tenantId) {
          config.headers[TENANT_HEADER] = tenantId
        }
      }
</#if>
      return config
    },
    (error) => Promise.reject(error)
  )

  instance.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
      const { data } = response
      if (data.code === 200) {
        return response
      }
      ElMessage.error(data.message || '操作失败')
      return Promise.reject(new Error(data.message || '操作失败'))
    },
    async (error) => {
      const { response: resp } = error
<#if enableSecurity>
      const authStore = useAuthStore()
      const requestConfig = error.config as RetriableRequestConfig | undefined

      if (resp?.status === 401) {
        if (requestConfig && !requestConfig._retry && authStore.canRefresh) {
          requestConfig._retry = true
          try {
            const tokenInfo = await authStore.refreshSession()
            requestConfig.headers = requestConfig.headers || {}
            requestConfig.headers.Authorization = `Bearer ${tokenInfo.accessToken}`
            const tenantId = authStore.getTenantId()
            if (tenantId) {
              requestConfig.headers[TENANT_HEADER] = tenantId
            }
            return instance(requestConfig)
          } catch (refreshError) {
            authStore.logout()
          }
        } else {
          authStore.logout()
        }

        if (router.currentRoute.value.name !== 'Login') {
          router.push({
            name: 'Login',
            query: { redirect: router.currentRoute.value.fullPath }
          })
        }
        ElMessage.error('登录状态已失效，请重新登录')
        return Promise.reject(error)
      }
</#if>

      let message = '请求失败'
      if (resp) {
        const { status, data } = resp
        const payload = data as ApiError | undefined
        switch (status) {
          case 400:
            message = payload?.message || '请求参数错误'
            break
          case 403:
            message = '没有权限执行该操作'
            break
          case 404:
            message = '请求的资源不存在'
            break
          case 500:
            message = '服务器内部错误'
            break
          default:
            message = payload?.message || `请求失败，状态码：${status}`
        }
      } else if (error.request) {
        message = '网络连接失败'
      }

      ElMessage.error(message)
      return Promise.reject(error)
    }
  )

  return instance
}

export const request = createRequest()
export default request
